<template>
  <div style="margin-left: 20px;margin-top: 20px">
    <div class="container">
      <el-input v-model="input" class="input-field" style="width: 300px" placeholder="请输入名称" />
      <el-button class="input-field" type="primary" icon="el-icon-search" @click="ck">查询</el-button>
      <el-button type="warning" icon="el-icon-circle-plus" @click="showFormxz">新增</el-button>

    </div>
    <br>

    <el-table v-loading="loading" :data="displayedData" style="">
      <el-table-column v-if="showColumnid" prop="estimateid" label="编号" />
      <el-table-column prop="estimatename" label="评估名称" />
      <el-table-column prop="estimateresults" label="评估结果" />
      <el-table-column prop="estimatesuggestions" label="建议" />
      <el-table-column v-if="showbz" prop="estimateremarks" label="备注" />
      <el-table-column prop="times" label="创建时间" />
      <el-table-column prop="estimaestatus" label="状态">
        <template v-slot="scope">
          {{ scope.row.estimaestatus === 0 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column prop="estimaestatus" label="操作">
        <!-- 使用v-for循环渲染按钮 -->
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" @click="showEditForm(scope.row.estimateid)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="open(scope.row.estimateid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>

    <el-pagination
      style="float: right"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog title="新增" :visible.sync="showForm">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="评估名称" prop="estimatename">
          <el-input v-model="ruleForm.estimatename" />
        </el-form-item>
        <el-form-item label="评估结果" prop="estimateresults">
          <el-input v-model="ruleForm.estimateresults" />
        </el-form-item>
        <el-form-item label="建议" prop="estimatesuggestions">
          <el-input v-model="ruleForm.estimatesuggestions" type="textarea" />
        </el-form-item>
        <el-form-item label="备注" prop="estimateremarks">
          <el-input v-model="ruleForm.estimateremarks" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="showFormxg">
      <el-form ref="rulexgForm" :model="rulexgForm" :rules="rules" label-width="100px">
        <el-form-item label="编号">
          <el-input v-model="rulexgForm.estimateid" readonly />
        </el-form-item>
        <el-form-item label="评估名称" prop="estimatename">
          <el-input v-model="rulexgForm.estimatename" />
        </el-form-item>
        <el-form-item label="评估结果" prop="estimateresults">
          <el-input v-model="rulexgForm.estimateresults" />
        </el-form-item>
        <el-form-item label="建议" prop="estimatesuggestions">
          <el-input v-model="rulexgForm.estimatesuggestions" type="textarea" />
        </el-form-item>
        <el-form-item label="备注" prop="estimateremarks">
          <el-input v-model="rulexgForm.estimateremarks" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="estimaestatus">
          <el-radio-group v-model="rulexgForm.estimaestatus">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormxg('rulexgForm')">确定</el-button>
          <el-button @click="resetFormxg('rulexgForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>
<style>

.container {
  display: flex;
  align-items: center;
}

.input-field {
  margin-right: 10px; /* 调整元素之间的间距 */

}

</style>
<script>
import row from 'element-ui/packages/row'
import axios from 'axios'
import getters from '@/store/getters'
export default {
  data() {
    return {

      message: '', // 返回结果成功没
      article: '',
      loading: true,
      input: '',
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      activeName: 'first',
      showFormxg: false, // 控制修改表单的显示
      showForm: false, // 控制添加表单的显示状态，默认隐藏
      showColumnid: false, // 控制id数据的隐藏
      showbz: false, // 控制备注数据隐藏
      displayedData: [], // 分页后的

      rulexgForm: {
        estimateid: '',
        estimatename: '',
        estimateresults: '',
        estimatesuggestions: '',
        estimateremarks: '',
        times: '',
        estimaestatus: ''
      },
      ruleForm: {
        estimatename: '',
        estimateresults: '',
        estimatesuggestions: '',
        estimateremarks: ''
      },

      rules: {
        estimatename: [
          { required: true, message: '请输入评估名称', trigger: 'blur' }
        ],
        estimateresults: [
          { required: true, message: '请输入评估结果', trigger: 'blur' }
        ],
        estimatesuggestions: [
          { required: true, message: '请填写建议', trigger: 'blur' }
        ],
        estimateremarks: [
          { required: true, message: '请填写备注', trigger: 'blur' }
        ]
      },
      rules2: {
        estimatename: [
          { required: true, message: '请输入评估名称', trigger: 'blur' }
        ],
        estimateresults: [
          { required: true, message: '请输入评估结果', trigger: 'blur' }
        ],
        estimatesuggestions: [
          { required: true, message: '请填写建议', trigger: 'blur' }
        ],
        estimateremarks: [
          { required: true, message: '请填写备注', trigger: 'blur' }
        ],
        estimaestatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }

    }
  },
  computed: {
    row() {
      return row
    }
  },
  mounted() {
    // 最初调用loadData()方法以填充表格
    const est = {}
    est.name = this.input
    this.fetchArticle(est)
  },
  methods: {
    open(id) {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'deletepgjy') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击 "确定" 按钮时执行删除操作
          this.deleteItem(id) // 传递 id 参数
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    deleteItem(id) {
      this.deletees(id)
      // 在这里执行删除操作，使用传递的 id 参数
      // 可以调用你的删除方法，传递 id 参数
      // 例如：this.$axios.delete(`/api/items/${id}`)
      // 然后处理成功和失败的情况
      // 成功：显示删除成功的消息
      // 失败：显示删除失败的消息
    },
    // 当每页显示条数发生变化时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      // 根据新的每页显示条数重新加载数据
      this.loadData()
    },

    // 当前页码发生变化时触发
    handleCurrentChange(val) {
      this.currentPage = val
      // 根据新的当前页码重新加载数据
      this.loadData()
    },
    // 根据当前页和每页显示的数量加载数据
    loadData() {
      console.log(this.article)
      const startIndex = (this.currentPage - 1) * this.pageSize// 得到当前页从哪一页显示的
      const endIndex = startIndex + this.pageSize// 得到下一页的页
      this.displayedData = this.article.slice(startIndex, endIndex)// （5，10）显示的是第二页的
      this.loading = false
    },
    // 确定添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')

          // 在验证通过后获取表单数据
          const formData = { ...this.ruleForm }
          console.log(formData)

          // 执行其他操作，例如发送表单数据到后端
          this.addes(formData)
          this.$refs[formName].resetFields()
          this.showForm = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 确定修改
    submitFormxg(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
          const formData = { ...this.rulexgForm }
          this.updatees(formData)
          this.$refs[formName].resetFields()
          this.showFormxg = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 显示添加页面
    showFormxz() {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'addpgjy') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        this.showForm = true
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    // 显示修改页面
    showEditForm(id) {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'updatepgjy') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        const data = this.displayedData.find((user) => user.estimateid === id)
        this.showFormxg = true
        // 给修改页面赋值
        this.rulexgForm.estimateid = data.estimateid
        this.rulexgForm.estimatename = data.estimatename
        this.rulexgForm.estimateresults = data.estimateresults
        this.rulexgForm.estimatesuggestions = data.estimatesuggestions
        this.rulexgForm.estimateremarks = data.estimateremarks
        this.rulexgForm.estimaestatus = data.estimaestatus.toString()
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    // 添加页面取消
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.showForm = false
    },
    // 修改页面取消
    resetFormxg(formName) {
      this.$refs[formName].resetFields()
      this.showFormxg = false
    },
    // 查询名称方法
    ck() {
      const est = {}
      est.name = this.input
      this.fetchArticle(est)
    },
    // 查询方法
    async fetchArticle(est) {
      console.log(est)
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/estimate/queryestimate', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        // eslint-disable-next-line no-unused-vars
        const { code, flag, message, data } = response.data
        this.article = data
        this.message = message
        this.totalItems = this.article.length
        this.loadData()
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async addes(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/estimate/addes', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async updatees(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/estimate/updatees', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async deletees(id) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post(`/api/estimate/deletees/${id}`, null, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        console.log(this.article)
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    }
  }

}

</script>
